package com.mmg.cosplay.entity;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.io.Serializable;

/**
 * 通用返回结果类 服务端响应的数据最终都会封装成此对象
 */
public class R<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private Integer code; //编码：200成功，500和其它数字为失败

    private String msg; //错误信息

    private T data; //数据

    /**
     * 成功带数据返回
     */
    public static <T> ResponseEntity success(T object) {
        R<T> r = new R<>();
        r.data = object;
        r.code = 200;
        return new ResponseEntity<>(r, HttpStatus.OK);
    }

    /**
     * 成功带消息和数据返回
     */
    public static <T> ResponseEntity success(String msg,T object) {
        R<T> r = new R<>();
        r.msg = msg;
        r.data = object;
        r.code = 200;
        return new ResponseEntity<>(r, HttpStatus.OK);
    }

    /**
     * 失败带数据返回
     */
    public static <T> ResponseEntity error(String msg) {
        R<T> r = new R<>();
        r.msg = msg;
        r.code = 500;
        return new ResponseEntity<>(r, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 失败带消息和数据返回
     */
    public static <T> ResponseEntity error(String msg,T object) {
        R<T> r = new R<>();
        r.msg = msg;
        r.data = object;
        r.code = 500;
        return new ResponseEntity<>(r, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "R{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}
